package com.ns.basic.dict.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ns.basic.dict.dto.DictPageDto;
import com.ns.basic.dict.entry.DictEntry;
import com.ns.basic.dict.mapper.DictEntryMapper;
import com.ns.basic.dict.mapper.DictItemEntryMapper;
import com.ns.basic.dict.vo.DiVO;
import com.ns.basic.dict.vo.DictEntryVO;
import com.ns.core.current.config.SysConst;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 字典业务实现层
 *
 * @author liaowei
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DictEntryServiceImpl extends ServiceImpl<DictEntryMapper, DictEntry> implements IDictEntryService {

    private final DictEntryMapper dictEntryMapper;

    private final DictItemEntryMapper dictItemEntryMapper;

    @Override
    public Page<DictEntryVO> selectBy(DictPageDto dto) {
        // 查询字典
        Page<DictEntryVO> dictPage = dictEntryMapper.selectBySearch(dto, new Page<>(dto.getCurrent(), dto.getSize()));
        List<DictEntryVO> records = dictPage.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            for (DictEntryVO rd : records) {
                rd.setItems(dictItemEntryMapper.selectByDictId(rd.getId()));
            }
        }
        // 组装数据
        return dictPage;
    }

    @Override
    @Cacheable(cacheNames = SysConst.PROJECT_TAG, key = "'" + SysConst.PROJECT_DICT + "'", unless = "#result==null")
    public Map<String, Map<String, Object>> listBy() {
        List<DiVO> dis = dictItemEntryMapper.listBy();
        Map<String, Map<String, Object>> mps = new HashMap<>();
        if (!CollectionUtils.isEmpty(dis)) {
            for (DiVO di : dis) {
                Map<String, Object> jos;
                if (mps.containsKey(di.getDc())) {
                    jos = mps.get(di.getDc());
                } else {
                    jos = new HashMap<>();
                }
                jos.put(di.getDic(), di.getDin());
                mps.put(di.getDc(), jos);
            }
        }
        return mps;
    }
}
